package com.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.hly.common.to.es.SkuEsModel;
import com.search.config.RequestElasticSearchConfig;
import com.search.constant.EsConstant;
import com.search.service.ShopSearchService;
import com.search.vo.SearchParam;
import com.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * es查询，条件筛选
 */
@Service
public class ShopSearchServiceImpl implements ShopSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     *
     * @param searchParam 请求参数封装类
     * @return 返回的结果集
     */
    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchResult result = new SearchResult();
        // 1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        try {
            // 2、执行检索请求
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestElasticSearchConfig.COMMON_OPTIONS);
            // 3、分析响应数据，封装成指定的格式
            result = buildSearchResult(response, searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建检索数据
     * 模糊匹配、过滤（按照属性、分类、品牌、价格区间、库存进行过滤）、排序、分页、高亮、聚合
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        // 构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 一、模糊匹配、过滤（按照属性、三级分类、品牌、价格区间、库存进行过滤）
         */
        // 1、构建bool
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 1.1、must-模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }

        // 1.2、filter-三级分类id
        if (param.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // 1.2、filter-品牌id
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // 1.2、filter-库存
        if(param.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        // 1.2、filter-属性
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            // 属性传递过来的格式：attrs=1_安卓:苹果:其他&attrs=2_5.6英寸以上:5.5-5.1英寸
            // 注意：每一个attr都得生成一个完整的nested查询
            for (String attr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();

                String[] s = attr.split("_");
                String attrId = s[0]; // 检索属性id

                nestedBoolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                String[] attrValues = s[1].split(":"); // 检索属性id对应的属性值
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //                                                      path: filter nested 在最后
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", nestedBoolQueryBuilder, ScoreMode.None);

                boolQueryBuilder.filter(nestedQueryBuilder);
            }
        }
        // 1.2、filter-价格区间
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            // 价格传递过来的格式：skuPrice=1_500/1_/_500
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) { // skuPrice=1_500/_500的情况
                if (param.getSkuPrice().startsWith("_")) {
                    // s[0]="",s[1]=500
                    rangeQueryBuilder.lte(Double.parseDouble(s[1]));
                } else {
                    rangeQueryBuilder.gte(Double.parseDouble(s[0])).lte(Double.parseDouble(s[1]));
                }
            } else if (s.length == 1) { // skuPrice=1_
                rangeQueryBuilder.gte(Double.parseDouble(s[0]));
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }

        // 封装上述查询条件
        sourceBuilder.query(boolQueryBuilder);



        /**
         * 二、排序、分页、高亮
         */
        // 2.1、排序
        if (!StringUtils.isEmpty(param.getSort())) {
            // 排序传递过来的格式：sort=saleCount_desc
            String[] sort = param.getSort().split("_");
            SortOrder order = sort[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(sort[0], order);
        }
        // 2.2、分页
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        // 2.3、高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.preTags("<b style='color: red'>");
            highlightBuilder.postTags("</b>");
            highlightBuilder.field("skuTitle");
            sourceBuilder.highlighter(highlightBuilder);
        }

        /**
         * 三、聚合
         */
        // 3.1、品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(20);
        // 品牌子聚合，品牌名称和品牌图片
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);

        // 3.2、三级分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        // 三级分类子聚合，三级分类名称
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);

        //3.3、属性聚合                                                             path : 指定 nested 属性（数组对象）
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");

        // 属性聚合子聚合，属性id
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(20);
        // 属性id子聚合，属性名称
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        // 属性id子聚合，属性id对应的属性值
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(20));
        attr_agg.subAggregation(attr_id_agg);

        sourceBuilder.aggregation(attr_agg);

        System.out.println("构建的DSL:" + sourceBuilder.toString());
        SearchRequest request = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
//        System.out.println("request = "+request+"  \t嘟嘟噜~");
        return request;
    }

    /**
     *
     * @param searchResponse 查询es返回值
     * @param searchParam 请求参数
     * @return
     */
    private SearchResult  buildSearchResult(SearchResponse searchResponse,SearchParam searchParam) {
        //返回的对象
        SearchResult result = new SearchResult();

        //1、返回的所有查询到的商品
        SearchHits hits = searchResponse.getHits();

        List<SkuEsModel> esModels = new ArrayList<>();
        if (null != hits.getHits() && hits.getHits().length > 0) {

            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);

                if (!StringUtils.isEmpty(searchParam.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    esModel.setSkuTitle(skuTitle.fragments()[0].string());
                }
                esModels.add(esModel);
            }
        }
        result.setProducts(esModels);

        //2、当前所有商品共同拥有的规格参数
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();

        //获取聚合结果
        ParsedNested attr_agg = searchResponse.getAggregations().get("attr_agg");
        //   attr_agg.getAggregations()
        //获取内层聚合结果
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");

        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //1、得到属性的id;
            long attrId = bucket.getKeyAsNumber().longValue();
            //2、得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            //3、得到属性的所有值(选中值)
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        //3、当前所有品牌涉及到的所有属性
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //1、得到品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            //2、得到品牌的名
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            //3、得到品牌的图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        //4、当前商品所涉及的分类信息
        ParsedLongTerms catalog_agg = searchResponse.getAggregations().get("catalog_agg");

        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));

            //得到分类名
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //===========以上从聚合信息获取到=============
        //5、分页信息-页码
        result.setPageNum(searchParam.getPageNum());
        //6、分页信息-总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //7、分页信息-总页码-计算
        int totalPages = total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : ((int) total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(totalPages);
        // 5.4、导航页码
        List<Integer> pageNav = new ArrayList<>();
        for (int i=1;i<=totalPages;i++) {
            pageNav.add(i);
        }
        result.setPageNavs(pageNav);

//        System.out.println("result = "+JSON.toJSONString(result)+" \t 嘟嘟噜~");
        return result;
    }

}